import { nanoid } from 'nanoid'

export const isDev = process.env.NODE_ENV === 'development'

// 判断变量是否为 null 或 undefined
export function isNullOrEmpty(value) {
  return value === null || value === undefined || value === ''
}

export function fillArrayWithPlaceholders(arr, targetLength, placeholder) {
  const filledArray = [...arr] // 创建原数组的副本

  while (filledArray.length < targetLength) {
    filledArray.push(placeholder)
  }

  return filledArray
}

export function chunkArray(arr, chunkSize) {
  const result = []
  for (let i = 0; i < arr.length; i += chunkSize) {
    result.push(arr.slice(i, i + chunkSize))
  }
  return result
}

export function componentID() {
  return nanoid()
}

/**
 * 获取叶子节点
 * @param tree
 * @param options
 * @returns {*[]}
 */
export function getLeafNodes(tree, options = {}) {
  const { childrenProp = 'children' } = options // 默认子节点属性名为 'children'

  const leafNodes = []

  function traverse(nodes) {
    nodes.forEach(node => {
      if (node[childrenProp] && node[childrenProp].length > 0) {
        // 如果节点有子节点，递归遍历子节点

        traverse(node[childrenProp])
      } else {
        // 如果没有子节点，该节点是叶子节点，添加到结果数组中

        leafNodes.push(node)
      }
    })
  }

  // 开始遍历树

  traverse(tree)

  // 返回叶子节点数组

  return leafNodes
}

export function flattenTree(tree) {
  const flatArray = []

  function traverse(node) {
    flatArray.push(node)
    if (node.children) {
      for (const child of node.children) {
        traverse(child)
      }
    }
  }

  for (const node of tree) {
    traverse(node)
  }

  return flatArray
}

/**
 * 获取URL参数
 * @param variable
 * @returns {string | Boolean}
 */
export function getQueryVariable(variable) {
  const query = window.location.search.substring(1)
  const vars = query.split('&')
  for (const item of vars) {
    const pair = item.split('=')
    if (pair[0] === variable) {
      return pair[1]
    }
  }
  return false
}
